﻿import com.gamepackage.tilemap.pathfinder.Headquarter;

class com.gamepackage.tilemap.pathfinder.Agent
{
	private var x: Number;
	private var y: Number;
	private var dir: Number;
	private var path: Array;

	private var hq: Headquarter;

	function Agent ( x: Number , y: Number , dir: Number , path: Array, hq: Headquarter )
	{
		this.x = x;
		this.y = y;
		this.dir = dir;
		this.path = path;
		this.hq = hq;
		
		hq.agents.push( this );
	}

	function move (): Boolean
	{
		var map: Array = hq.map;
		var occ: Array = hq.occ;

		if ( map[ y ][ x ] == undefined ) { return false; };
		if ( occ[ y ][ x ] ) { return false; };

		if ( x == hq.x1 && y == hq.y1 )
		{
			hq.pathFound = true;
			hq.foundPath = path;
			return true;
		}

		if ( occ[ y ] == undefined ) { occ[ y ] = []; };
		occ[ y ][ x ] = true;
		
		if ( dir == 1 ) {
			if ( ~map[ y + 1 ][ x ] & 1 ) new Agent ( x, y + 1, 4, path.concat ( [ { x: x , y: y + 1 } ] ), hq );
			if ( ~map[ y - 1 ][ x ] & 1 ) new Agent ( x, y - 1, 8, path.concat ( [ { x: x , y: y - 1 } ] ), hq );
			if ( ~map[ y ][ x + 1 ] & 1 )
			{
				path.push ( { x: ++x , y: y } );
				return true;
			}
			return false;
		} else if ( dir == 2 ) {
			if ( ~map[ y + 1 ][ x ] & 1 ) new Agent ( x, y + 1, 4, path.concat ( [ { x: x , y: y + 1 } ] ), hq );
			if ( ~map[ y - 1 ][ x ] & 1 ) new Agent ( x, y - 1, 8, path.concat ( [ { x: x , y: y - 1 } ] ), hq );
			if ( ~map[ y ][ x - 1 ] & 1 )
			{
				path.push ( { x: --x , y: y } );
				return true;
			};
			return false;
		} else if ( dir == 4 ) {
			var yMap = map[y];
			if ( ~yMap[ x + 1 ] & 1 ) new Agent ( x + 1, y, 1, path.concat ( [ { x: x + 1 , y: y } ] ), hq );
			if ( ~yMap[ x - 1 ] & 1 ) new Agent ( x - 1, y, 2, path.concat ( [ { x: x - 1 , y: y } ] ), hq );
			if ( ~map[ y + 1 ][ x ] & 1 )
			{
				path.push ( { x: x , y: ++y } );
				return true;
			};
			return false;
		}
		// else ( dir == 8 )
		var yMap = map[y];
		if ( ~yMap[ x + 1 ] & 1 ) new Agent ( x + 1, y, 1, path.concat ( [ { x: x + 1 , y: y } ] ), hq );
		if ( ~yMap[ x - 1 ] & 1 ) new Agent ( x - 1, y, 2, path.concat ( [ { x: x - 1 , y: y } ] ), hq );
		if ( ~map[ y - 1 ][ x ] & 1 )
		{
			path.push ( { x: x , y: --y } );
			return true;
		};
		return false;
	}
}